import axios from 'axios'
import qs from 'qs'

import * as _ from '../util/tool'
import router from '../router/router'
import store from '../store/store'
import * as types from '../store/types'
import request from './request.js'

// axios 配置
axios.defaults.timeout = 60000
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'//'application/json' //
axios.defaults.baseURL = env.BASE_API

// POST传参序列化
axios.interceptors.request.use((config) => {
  if (config.method === 'post') {
    console.log('config.data')
    console.log(config.data)
    //config.data = qs.stringify(config.data)
  }

  if (store.state.token) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
    config.headers.Authorization = `${store.state.token}`
  }
  if (store.state.appKey) {
    config.headers.appKey = `${store.state.appKey}`
  }
  return config
}, (error) => {
  _.toast('错误的传参', 'fail')
  return Promise.reject(error)
})

// 返回状态判断
axios.interceptors.response.use((res) => {
  if(res.headers.token){
    //如果后台通过header返回token，说明token已经更新，则更新客户端本地token
    store.commit('RESETTOKEN',{token:res.headers.token})
  }
  if (res.headers['content-type'] === 'images/jpeg') {
    return res
  }
  return res
}, (error) => {
  if (error.response) {
    console.log("请求出错")
    switch (error.response.status) {
      case 401:
        // 返回 401 清除token信息并跳转到登录页面
        console.log("走清除token")
        store.commit(types.LOGOUT)
        window.localStorage.removeItem("token")
        window.localStorage.removeItem("account")
        window.localStorage.setItem('referrer', router.currentRoute.fullPath)
        router.replace({
          path: 'login',
          query: {redirect: router.currentRoute.fullPath}
        })

        break
      case 500:
        /* router.replace({
          path: 'error',
          query: {redirect: router.currentRoute.fullPath}
        }) */
        break
    }
  }
  _.toast('网络异常', 'fail')
  return Promise.reject(error)
})

export function post (url, params) {
  return new Promise((resolve, reject) => {
    console.log("打印参数")
    console.log(params)
    axios.post(url, qs.stringify(params))
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

export function newpost (url, data) {
  return new Promise((resolve, reject) => {
    data = JSON.stringify(data)
    console.log("打印参数")
    console.log(data)
    axios({
      method: 'post',
      baseURL: env.BASE_API,
      url: url,
      headers: {
        'Content-Type': 'application/json',
        'X-Custom-Header': 'foobar' ,
      },
      data: data,
    }).then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

export function twicepost (url, data) {
  return new Promise((resolve, reject) => {
    console.log("打印参数")
    axios.post(url,data,
      {headers:{
        'X-Custom-Header': 'foobar',
      }})
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

export function get (url, params) {
  return new Promise((resolve, reject) => {
    // console.log(params)
    axios.get(url, params)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

export function imgPost (url, data) {
  return new Promise((resolve, reject) => {
    const upload = axios.create({ baseURL: env.BASE_API, timeout: 5000,})
    upload({
      url: '/file',
      method: 'post',
      headers: {
        "Authorization": `${store.state.token}`,
        "Content-Type": "multipart/form-data",
      },
      data: data,
    }).then(response => {
      resolve(response.data)
      //return(response)
    }, err => {
      reject(err)
    })
    .catch((error) => {
      reject(error)
    })
  })
}

export default {

  dologin(params){
    console.log(params)
    return post('/h5/user/login', params)
  },
  getAccount(){
    return get('/h5/getMyDate')//get('/h5/user/getUserInfo')
  },
  getMoneyInfo(params){
    return request({
      url: '/h5/getMoneyInfo',
      method: 'get',
      params
    })
  },
  doregister(params){
    return post('/h5/user/register', params)
  },
  updateInfo(params){
    return request({
      url: '/h5/user/updateInfo',
      method: 'post',
      headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
      params
    })
  },
  updatePassword(){
    return request({
      url: '/h5/user/updatePassword',
      method: 'post',
      headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
      params
    })
  },
  //index
  getIndexInfo(){
    return get('/h5/index/getIndexInfo')
  },
  getTaskList(params){
    return request({
      url: '/h5/index/getTaskList',
      method: 'get',
      params
    })
  },
  //充值
  payVip(params){
    return request({
      url: '/h5/payVip',
      method: 'post',
      headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
      params
    })
  },
  //
  getUserCityInfo(){
    return get('/h5/index/getUserCityInfo')
  },


  getGetAllCity(address){
    return get('/h5/index/getCityInfo?city='+address)
  },
  getmyhelptask(params){
    return request({
      url: '/h5/task/getMyHelpTask',
      method: 'get',
      params
    })
  },
  addtask(param){
    return newpost('/h5/task/add', param)
  },
  edittask(params){
    return newpost('/h5/task/edit', params)
  },
  getTaskDetail(params){
    return request({
      url: '/h5/task/getTaskDetail',
      method: 'get',
      params
    })
  },
  doskilltask(params){
    return request({
      url: '/h5/taskOrder/add',
      method: 'get',
      params
    })
  },
  setState(params){
    return request({
      url: '/h5/task/setState',
      method: 'get',
      params
    })
  },
  getCost(params){
    return request({
      url: '/h5/task/getCost',
      method: 'get',
      params
    })
  },
  pay(params){
    return request({
      url: '/h5/pay',
      method: 'post',
      headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
      params
    })
  },
  withdraw(params){
    return request({
      url: '/h5/withdraw',
      method: 'post',
      headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
      params
    })
  },
  audit(params){
    return request({
      url: '/h5/taskOrder/audit',
      method: 'get',
      params
    })
  },
  myAudit(params){
    return request({
      url: '/h5/taskOrder/myAudit',
      method: 'get',
      params
    })
  },
  getMyOrderList(params){
    return request({
      url: '/h5/taskOrder/myOrderList',
      method: 'get',
      headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
      params
    })
  },
  gettaskOrderDetail(params){
    return request({
      url: '/h5/taskOrder/getOrderDetail',
      method: 'get',
      headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
      params
    })
  },
  submitProof(params){
    /* return request({
      url: '/h5/taskOrder/submitProof',
      method: 'post',
      headers: {'Content-Type': 'application/json'},
      data: params
    }) */
    return newpost('/h5/taskOrder/submitProof', params)
  },

  appeal(params){
    return request({
      url: '/h5/taskOrder/appeal',
      method: 'get',
      headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
      params
    })
  },

  waiveOrder(params){
    return request({
      url: '/h5/taskOrder/waiveOrder',
      method: 'get',
      headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
      params
    })
  },


  getUlist(){
    return post('')
  },

  getOffcialSite () {
    return get('/offcialsite')
  },
  getProductList () {
    return get('/offcialsite/product')
  },

  getSolutionList () {
    return get('/offcialsite/solution')
  },

  getCaseList () {
    return get('/offcialsite/case')
  },
  getNewsList () {
    return get('/offcialsite/news')
  },
  getArticle (id, type) {
    return get('/offcialsite/article?id=' + id + '&type=' + type)
  },
  saveContact (params) {
    return post('/offcialsite/contact', params)
  },
  uploadImg (data){
    return imgPost('/file', data)
  }

}
